package com.digiwin;

import com.digiwin.demo.vo.VisitVO;
import com.google.gson.Gson;
import com.rabbitmq.client.*;

import java.util.Date;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author yanggld
 * @Date 2019/12/23-14:17
 * @Description
 */
public class DataCreater {

	private static final String EXCHANGE_NAME = "exchange_demo";
	private static final String ROUTING_KEY   = "es.book";
//	private static final String QUEUE_NAME    = "queue_demo_1";
	private static final String IP_ADDRESS    = "172.16.1.198";
	private static final int    PORT          = 5672;

	public static void main(String[] args) {
		try {
			ConnectionFactory factory = new ConnectionFactory();
			factory.setHost(IP_ADDRESS);
			factory.setPort(PORT);
			factory.setUsername("guest");
			factory.setPassword("guest");
			//创建连接
			Connection connection = null;
			connection = factory.newConnection();
			//创建信道
			Channel channel = connection.createChannel();
			//创建一个type="direct"、持久化的、非自动删除的交换器
			channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC, true, false, null);
			//创建一个持久化、非排他的、非自动删除的队列
//			channel.queueDeclare(QUEUE_NAME, true, false, false, null);
			//将交换器与队列通过路由键绑定
//			channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);
			//发送一条持久化的消息：hello world！
			int i = 0;
			while(i < 1){
				i ++ ;
				VisitVO vo = new VisitVO();
				vo.setCount(1);
				vo.setDate(new Date());
				int idRandom = ThreadLocalRandom.current().nextInt(10);
				vo.setUid("用户-"+idRandom);
				int bookRandom = ThreadLocalRandom.current().nextInt(10);
				vo.setName("book-"+bookRandom);
				Gson gson = new Gson();
				String dataStr =gson.toJson(vo);
				channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY, MessageProperties.PERSISTENT_TEXT_PLAIN, dataStr.getBytes());
				System.out.println(i+":"+dataStr);
				Thread.sleep(100);
			}
			//关闭资源
			channel.close();
			connection.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
